/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.x3.purchasing.index;

import com.x3.purchasing.account.Account;
import com.x3.purchasing.common.ClassApplicationModule;
import com.x3.purchasing.inquery.Inquery;
import com.x3.purchasing.inquery.InqueryDAO;
import com.x3.purchasing.inquery.InqueryDAOImpl;
import com.x3.purchasing.kategori.Kategori;
import com.x3.purchasing.kategori.KategoriDAO;
import com.x3.purchasing.kategori.KategoriDAOImpl;
import com.x3.purchasing.operator.Operator;
import com.x3.purchasing.operator.OperatorDAO;
import com.x3.purchasing.operator.OperatorDAOImpl;
import com.x3.purchasing.order.OrderDAO;
import com.x3.purchasing.order.OrderDAOImpl;
import com.x3.purchasing.order.OrderDetailDAO;
import com.x3.purchasing.order.OrderDetailDAOImpl;
import com.x3.purchasing.produk.Produk;
import com.x3.purchasing.produk.ProdukDAO;
import com.x3.purchasing.produk.ProdukDAOImpl;
import com.x3.purchasing.role.Menu;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zkoss.image.AImage;
import org.zkoss.image.Image;
import org.zkoss.zhtml.Messagebox;
import org.zkoss.zul.Div;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Panel;
import org.zkoss.zul.Panelchildren;
import org.zkoss.zul.Row;
import org.zkoss.zul.Rows;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Vbox;
import org.zkoss.zul.Window;

/**
 *
 * @author Hendro Steven
 */
public class IndexWnd extends ClassApplicationModule {

    Div contentDiv;
    Session session;
    Account acc;
    Vbox panelMenu;
    Vbox panelUserMenu;
    Textbox textboxSearch;
    Grid gridKatalok;
    Grid gridInquery;
    Panel panelKatalok;
    Panel panelInquery;
    Panelchildren panelChildKatalok;
    Panelchildren panelChildInquery;
    Rows rowsKatalok = new Rows();
    Rows rowsInquery = new Rows();
    KategoriDAO kategoriDAO;
    ProdukDAO produkDAO;
    InqueryDAO inqueryDAO;
    OrderDetailDAO orderDetailDAO;
    OperatorDAO operatorDAO;
    OrderDAO orderDAO;

    public void onCreate() throws Exception {
        contentDiv = (Div) getFellow("contentDiv");
        panelMenu = (Vbox) getFellow("panelMenu");
        panelUserMenu = (Vbox) getFellow("panelUserMenu");
        textboxSearch = (Textbox) getFellow("textboxSearch");
        gridKatalok = (Grid) getFellow("gridKatalok");
        panelKatalok = (Panel) getFellow("panelKatalok");
        panelChildKatalok = (Panelchildren) getFellow("panelChildKatalok");
        panelChildInquery = (Panelchildren) getFellow("panelChildInquery");
        panelInquery = (Panel) getFellow("panelInquery");
        gridInquery = (Grid) getFellow("gridInquery");
        kategoriDAO = new KategoriDAOImpl();
        produkDAO = new ProdukDAOImpl();
        operatorDAO = new OperatorDAOImpl();
        inqueryDAO = new InqueryDAOImpl();
        orderDAO = new OrderDAOImpl();
        orderDetailDAO = new OrderDetailDAOImpl();

        this.loadMenu();
        this.loadInquery();
        this.loadKatalok();
//        session = Sessions.getCurrent();
//        Account account = new Account();
//        account.setId(13);
//        session.setAttribute("ACC_LOGIN", account);

//        acc = (Account) session.getAttribute("ACC_LOGIN");
//        if (acc != null) {
//            createMenu();
//            createUserMenu();
//        } else {
//            createDefaultMenu();
//            createDefaultUserMenu()
//        }
//        showObject("/zul/Home.zul");

        //Test

        session = Sessions.getCurrent();
        acc = (Account) session.getAttribute("ACC_LOGIN");
        if (acc != null) {
            createMenu();
            //createUserMenu();
        } else {
            //createDefaultMenu();
            createDefaultUserMenu();
        }
        //showObject("/zul/Home.zul");

    }

//    private void createDefaultMenu() throws Exception {
//        try {
//            panelMenu.getChildren().clear();
//            RoleDAO dao = new RoleDAOImpl();
//            List<Menu> menus = dao.getDefaultMenus();
//            for (final Menu mnu : menus) {
//                Toolbarbutton barMenu = new Toolbarbutton(mnu.getLabel());
//                barMenu.setImage("/img/item.png");
//                barMenu.addEventListener("onClick", new EventListener() {
//
//                    public void onEvent(Event event) throws Exception {
//                        contentDiv.getChildren().clear();
//                        Executions.createComponents(mnu.getPath(), contentDiv, null);
//                    }
//                });
//                panelMenu.appendChild(barMenu);
//            }
//        } catch (Exception ex) {
//            Messagebox.show(ex.getMessage());
//        }
//    }
    private void createDefaultUserMenu() throws Exception {
        // System.out.println("OKOK");
        panelUserMenu.getChildren().clear();
        Toolbarbutton barMenu1 = new Toolbarbutton("Login");
        //barMenu1.setImage("/img/login.png");
        barMenu1.addEventListener("onClick", new EventListener() {

            public void onEvent(Event event) throws Exception {
                login();
            }
        });
        panelUserMenu.appendChild(barMenu1);

        Toolbarbutton barMenu2 = new Toolbarbutton("Registrasi");
        //barMenu2.setImage("/img/registrasi.png");
        barMenu2.addEventListener("onClick", new EventListener() {

            public void onEvent(Event event) throws Exception {
                contentDiv.getChildren().clear();
                Executions.createComponents("/zul/VendorRegistrasi.zul", contentDiv, null);
            }
        });
        panelUserMenu.appendChild(barMenu2);
    }

    private void createMenu() {
        panelUserMenu.getChildren().clear();
        Toolbarbutton barMenuLogout = new Toolbarbutton("Logout");
        barMenuLogout.addEventListener("onClick", new EventListener() {

            public void onEvent(Event event) throws Exception {
                logout();
            }
        });
        panelUserMenu.appendChild(barMenuLogout);
        for (final Menu mnu : acc.getRole().getMenus()) {
            Toolbarbutton barMenu = new Toolbarbutton(mnu.getLabel());
            //barMenu.setImage("/img/item.png");
            barMenu.addEventListener("onClick", new EventListener() {

                public void onEvent(Event event) throws Exception {
                    contentDiv.getChildren().clear();
                    Executions.createComponents(mnu.getPath(), contentDiv, null);
                }
            });
            panelUserMenu.appendChild(barMenu);
        }
    }

//    private void createUserMenu() throws Exception {
//        panelUserMenu.getChildren().clear();
//        Div div = new Div();
//        Vbox vbox = new Vbox();
//        vbox.setAlign("center");
//
//        Label lbl1 = new Label();
//        lbl1.setValue("Selamat Datang");
//
//        Label lbl2 = new Label();
//        lbl2.setStyle("font-size:12px");
//        lbl2.setValue("# " + acc.getUsername() + " #");
//
//        vbox.appendChild(lbl1);
//        vbox.appendChild(lbl2);
//        div.appendChild(vbox);
//        panelUserMenu.appendChild(div);
//        Toolbarbutton barMenu1 = new Toolbarbutton("Logout");
//        //barMenu1.setImage("/img/login.png");
//        barMenu1.addEventListener("onClick", new EventListener() {
//
//            public void onEvent(Event event) throws Exception {
//                logout();
//            }
//        });
//        panelUserMenu.appendChild(barMenu1);
//
//        if (acc.getRole().getId() == 3) {
//            Toolbarbutton barMenu3 = new Toolbarbutton("Ubah Profil");
//            //barMenu3.setImage("/img/profil.png");
//            barMenu3.addEventListener("onClick", new EventListener() {
//
//                public void onEvent(Event event) throws Exception {
//                    contentDiv.getChildren().clear();
//                    Executions.createComponents("/zul/ProfilePerusahaan.zul", contentDiv, null);
//                }
//            });
//            panelUserMenu.appendChild(barMenu3);
//        }
//
//        Toolbarbutton barMenu2 = new Toolbarbutton("Registrasi");
//        barMenu2.setImage("/img/registrasi.png");
//        barMenu2.addEventListener("onClick", new EventListener() {
//
//            public void onEvent(Event event) throws Exception {
//                contentDiv.getChildren().clear();
//                Executions.createComponents("/zul/RegistrasiPerusahaan.zul", contentDiv, null);
//            }
//        });
//        panelUserMenu.appendChild(barMenu2);
//    }
    public void loadMenu() {
        try {
            panelMenu.getChildren().clear();
            List<Kategori> kategoris = kategoriDAO.gets();
            for (final Kategori kategori : kategoris) {
                Toolbarbutton toolbarbutton = new Toolbarbutton();
                toolbarbutton.setLabel(kategori.getNama());
                toolbarbutton.addEventListener("onClick", new EventListener() {

                    public void onEvent(Event event) throws Exception {
                        contentDiv.getChildren().clear();
                        int count = produkDAO.countKategori(kategori.getId());
                        int start = 0;
                        int end = 0;
                        List<Produk> produks = new ArrayList<Produk>();
                        if (count > 5) {
                            start = count - 5;
                            end = 5;
                            produks = produkDAO.gets(start, end);
                        } else {
                            start = 0;
                            end = 5;
                            produks = produkDAO.gets(start, end);
                        }
                        loadKatalokByKategori(produkDAO.getByKategori(kategori.getId(), start, end));
                    }
                });
                panelMenu.appendChild(toolbarbutton);
            }
        } catch (Exception ex) {
            Logger.getLogger(IndexWnd.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void loadKatalok() throws Exception {
//        List<Produk> count = produkDAO.gets();
//        List<Produk> produks = new ArrayList<Produk>();
//        if (count.size() > 5) {
//            int start = count.size() - 5;
//            int end = 5;
//            produks = produkDAO.gets(start, end);
//        } else {
//            int start = 0;
//            int end = 5;
//            produks = produkDAO.gets(start, end);
//        }
        List<Produk> produks = new ArrayList<Produk>();
        //Param not in use
        produks = produkDAO.gets(0, 0);
        if (gridKatalok.getRows() != null) {
            gridKatalok.getRows().getChildren().clear();
        }
        for (final Produk produk : produks) {
            Row row = new Row();
            Hbox hbox = new Hbox();
            if (produk.getFileGambar() != null) {
                if (produk.getFileGambar().available() > 0) {
                    Image image = new AImage("image", produk.getFileGambar());
                    org.zkoss.zul.Image img = new org.zkoss.zul.Image();
                    img.setContent(image);
                    img.setHeight("120px");
                    img.setWidth("150px");
                    hbox.appendChild(img);
                }
            } else {
                Label lblError = new Label("Gambar tidak tersedia");
                lblError.setStyle("color:red;");
                hbox.appendChild(lblError);
            }

            Vbox vbox = new Vbox();
            Label lblJudul = new Label(produk.getNama());
            lblJudul.setStyle("font-size:12px;font-weight:bold");
            vbox.appendChild(lblJudul);
            vbox.appendChild(new Label(produk.getKeteranganLengkap()));
            Toolbarbutton btnOrder = new Toolbarbutton();
            btnOrder.setTooltiptext("Add to cart");
            btnOrder.setImage("/img/add_cart.gif");
            btnOrder.addEventListener("onClick", new EventListener() {

                public void onEvent(Event event) throws Exception {
                    if (acc != null) {
                        if (acc.getRole().getId() == 0 || acc.getRole().getId() == 2) {
                            Messagebox.show("Maaf, Anda tidak dapat melakukan transaksi pembelian");
                        } else if (acc.getRole().getId() == 1) {
                            session.setAttribute("produk_id", produk.getId());
                            showObject("/zul/Order.zul");
                        }
                    } else {
                        Messagebox.show("Anda harus login terlebih dahulu");
                    }
                }
            });
            vbox.appendChild(btnOrder);
            hbox.appendChild(vbox);
            row.appendChild(hbox);
            rowsKatalok.appendChild(row);
            gridKatalok.appendChild(rowsKatalok);
            panelChildKatalok.appendChild(gridKatalok);
            panelKatalok.setTitle("Katalog Terbaru");
            panelKatalok.appendChild(panelChildKatalok);
            contentDiv.appendChild(panelKatalok);
        }
    }

    private void loadInquery() throws Exception {
//        List<Inquery> count = inqueryDAO.gets();
//
//        if (count.size() > 5) {
//            int start = count.size() - 5;
//            int end = 5;
//            inquerys = inqueryDAO.gets(start, end);
//        } else {
//            int start = 0;
//            int end = 5;
//            inquerys = inqueryDAO.gets(start, end);
//        }
        List<Inquery> inquerys = new ArrayList<Inquery>();
        //Param not in use
        inquerys = inqueryDAO.gets(0, 0);
        if (gridInquery.getRows() != null) {
            gridInquery.getRows().getChildren().clear();
        }
        for (final Inquery inquery : inquerys) {
            Row rowTitle = new Row();
            Row rowBody = new Row();
            Hbox hbox = new Hbox();

            Label lblJudul = new Label(inquery.getJudul());
            lblJudul.setStyle("font-size:12px;font-weight:bold");
            hbox.appendChild(lblJudul);
            rowTitle.appendChild(hbox);

            Vbox vbox = new Vbox();
            Toolbarbutton btnDetail = new Toolbarbutton();
            btnDetail.setTooltiptext("Add to cart");
            btnDetail.setStyle("font-size:9px;color:#0000FF;");
            btnDetail.setLabel("detail...");
            btnDetail.addEventListener("onClick", new EventListener() {

                public void onEvent(Event event) throws Exception {
                    session.setAttribute("idInquery", inquery.getId());
                    showObject("/zul/InqueryDetail.zul");
                }
            });
            Label lblBody = new Label();
            lblBody.setValue(inquery.getKeterangan());
            vbox.appendChild(lblBody);
            vbox.appendChild(btnDetail);
            rowBody.appendChild(vbox);

            rowsInquery.appendChild(rowTitle);
            rowsInquery.appendChild(rowBody);
            gridInquery.appendChild(rowsInquery);
            panelChildInquery.appendChild(gridInquery);
            panelInquery.appendChild(panelChildInquery);
            contentDiv.appendChild(panelInquery);
        }
    }

    private void loadKatalokByKategori(List<Produk> produks) throws IOException, Exception {
        //this.loadInquery();
        if (gridKatalok.getRows() != null) {
            gridKatalok.getRows().getChildren().clear();
        }
        if (produks.isEmpty()) {
            Messagebox.show("Barang pada kategori tersebut belum tersedia");
        }
        for (final Produk produk : produks) {
            Row row = new Row();
            Hbox hbox = new Hbox();
            if (produk.getFileGambar() != null) {
                if (produk.getFileGambar().available() > 0) {
                    Image image = new AImage("image", produk.getFileGambar());
                    org.zkoss.zul.Image img = new org.zkoss.zul.Image();
                    img.setContent(image);
                    img.setHeight("120px");
                    img.setWidth("150px");
                    hbox.appendChild(img);
                }
            } else {
                Label lblError = new Label("Gambar tidak tersedia");
                lblError.setStyle("color:red;");
                hbox.appendChild(lblError);
            }

            Vbox vbox = new Vbox();
            Label lblJudul = new Label(produk.getNama());
            lblJudul.setStyle("font-size:12px;font-weight:bold");
            vbox.appendChild(lblJudul);
            Toolbarbutton btnOrder = new Toolbarbutton();
            btnOrder.setTooltiptext("Add to cart");
            btnOrder.setImage("/img/add_cart.gif");
            btnOrder.addEventListener("onClick", new EventListener() {

                public void onEvent(Event event) throws Exception {
                    if (acc != null) {
                        if (acc.getRole().getId() == 0 || acc.getRole().getId() == 2) {
                            Messagebox.show("Maaf, Anda tidak dapat melakukan transaksi pembelian");
                        } else if (acc.getRole().getId() == 1) {
                            session.setAttribute("produk_id", produk.getId());
                            showObject("/zul/Order.zul");
                        }
                    } else {
                        Messagebox.show("Anda harus login terlebih dahulu");
                    }
                }
            });
            vbox.appendChild(new Label(produk.getKeteranganLengkap()));
            vbox.appendChild(btnOrder);
            hbox.appendChild(vbox);
            row.appendChild(hbox);
            rowsKatalok.appendChild(row);
            gridKatalok.appendChild(rowsKatalok);
            panelChildKatalok.appendChild(gridKatalok);
            panelKatalok.setTitle("Katalog");
            panelKatalok.appendChild(panelChildKatalok);
            contentDiv.appendChild(panelKatalok);
        }
    }

    public void depan() throws Exception {
        contentDiv.getChildren().clear();
        this.loadInquery();
        this.loadKatalok();
        this.loadMenu();
    }

    public void search() throws Exception {
//        showObject("/zul/InformasiLelang.zul");
//        SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy");
//        DecimalFormat decimalFormat = new DecimalFormat("Rp ,##0.00");
//        Listbox listboxData = (Listbox) this.getFellow("listboxData");
//        listboxData.getItems().clear();
//        PekerjaanDAO pekerjaanDAO = new PekerjaanDAOImpl();
//        List<Pekerjaan> pekerjaans = pekerjaanDAO.search(textboxSearch.getText());
//        int no = 1;
//        for (final Pekerjaan pekerjaan : pekerjaans) {
//            Listitem listitem = new Listitem();
//            listitem.appendChild(new Listcell(no + ""));
//            listitem.appendChild(new Listcell(pekerjaan.getNamaPaketPekerjaan()));
//            listitem.appendChild(new Listcell(decimalFormat.format(pekerjaan.getPaguDana())));
//            listitem.appendChild(new Listcell(dateFormat.format(pekerjaan.getPendaftaranMulai()) + " s/d " + dateFormat.format(pekerjaan.getPendaftaranSelesai())));
//            Toolbarbutton btnDetail = new Toolbarbutton();
//            btnDetail.setId("btnDetail" + no);
//            btnDetail.setTooltiptext("Klik untuk melihat detail data");
//            btnDetail.setImage("/img/detail.png");
//            btnDetail.addEventListener("onClick", new EventListener() {
//
//                public void onEvent(Event event) throws Exception {
//                    showDetail(pekerjaan.getId());
//                }
//            });
//
//            Listcell cellAction = new Listcell();
//            cellAction.appendChild(btnDetail);
//            listitem.appendChild(cellAction);
//            listboxData.appendChild(listitem);
//            no++;
//        }
    }

    private void showDetail(int i) throws Exception {
    }

    private void logout() {
        session.removeAttribute("ACC_LOGIN");
        Executions.sendRedirect("/index.zul");
    }

    public void showObject(String objName) throws Exception {
        contentDiv.getChildren().clear();
        Executions.createComponents(objName, contentDiv, null);
    }

    public void login() throws InterruptedException {
        final Window win = (Window) Executions.createComponents("/zul/Login.zul", this, null);
        win.doModal();
    }
}
